package study.websocket.server.服务端;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import main.java.study.websocket.entity.vo.ApiProductionBatchVo;
import study.websocket.entity.vo.ApiAccessVo;
import study.websocket.entity.vo.ApiDataVo;
import study.websocket.entity.vo.ApiDeviceListVo;
import study.websocket.entity.vo.ApiDeviceVo;

// 定义 WebSocket 服务端
@Slf4j
@ServerEndpoint("/ws")
public class WebSocketServer2 {

    // 存储所有连接的客户端会话
    private static final CopyOnWriteArraySet<Session> clients = new CopyOnWriteArraySet<>();

    // 客户端连接时触发
    @OnOpen
    public void onOpen(Session session) {
        clients.add(session);
        System.out.println("New connection: " + session.getId());
        try {
            session.getBasicRemote().sendText("Welcome! You are connected.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 接收到客户端消息时触发
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Received message: " + message + " from " + session.getId());
        ApiAccessVo receiveVO = JSONUtil.toBean(message, ApiAccessVo.class);
        log.info("receiveVO:{}", receiveVO);

        try {

            if ("get_device_status".equals(receiveVO.getMsg_type())) {

                // 回复客户端消息
                ApiAccessVo apiAccessVo = new ApiAccessVo();
                apiAccessVo.setCode(0);
                apiAccessVo.setMsg_type("get_device_status");
                apiAccessVo.setMessage("13");
                ApiDeviceListVo apiDataVo = new ApiDeviceListVo();
                List<ApiDeviceVo> apiDeviceVoList = new ArrayList<>();
                ApiDeviceVo apiDeviceVo = new ApiDeviceVo();
                apiDeviceVo.setDevId(2);
                apiDeviceVo.setDeviceName("矩阵培养系统");
                apiDeviceVo.setDeviceType(1);
                apiDeviceVo.setDeviceModel("MCS001");
                apiDeviceVo.setDeviceSn("MCS240001");
                apiDeviceVo.setStatus(1);
                apiDeviceVoList.add(apiDeviceVo);
                apiDataVo.setDevices(apiDeviceVoList);
                apiAccessVo.setData(apiDataVo);
                String jsonStr = JSONUtil.toJsonStr(apiAccessVo);
                session.getBasicRemote().sendText(jsonStr);


            }else if ("get_unfinished_task".equals(receiveVO.getMsg_type())) {


                // 回复客户端消息
                ApiAccessVo apiAccessVo = new ApiAccessVo();
                apiAccessVo.setCode(0);
                apiAccessVo.setMsg_type("get_unfinished_task");
                apiAccessVo.setMessage("12");
                ApiDataVo apiDataVo = new ApiDataVo();
                List<ApiProductionBatchVo> apiProductionBatchVoList = new ArrayList<>();
                ApiProductionBatchVo apiProductionBatchVo = new ApiProductionBatchVo();
                apiProductionBatchVo.setActionStartTime("2021-01-01 00:00:00");
                apiProductionBatchVo.setOper_user("小刘");
                apiProductionBatchVo.setTask_code("201412110002");
                apiProductionBatchVo.setTemplate_name("MSC");
                apiProductionBatchVo.setStatus("2");
                apiProductionBatchVo.setStageName("P3传P4");
                apiProductionBatchVo.setScii_cellCode("123");
                apiProductionBatchVo.setScii_seedCellRemark("北科");
//            apiProductionBatchVo.setBagNum("10");
                apiProductionBatchVo.setProgressRate("100");
                apiProductionBatchVo.setOperSeqName("MSC细胞自动化流程");
                apiProductionBatchVo.setStart_time("2021-01-01 00:00:00");
                apiProductionBatchVo.setProcessEndTime("2021-01-07 00:00:00");
                apiProductionBatchVoList.add(apiProductionBatchVo);
                apiProductionBatchVoList.add(apiProductionBatchVo);
                apiDataVo.setTask_list(apiProductionBatchVoList);
                apiAccessVo.setData(apiDataVo);
                String jsonStr = JSONUtil.toJsonStr(apiAccessVo);
                session.getBasicRemote().sendText(jsonStr);

                // 广播消息给其他客户端
//            broadcast("Client " + session.getId() + " says: " + message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 客户端断开连接时触发
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        clients.remove(session);
        System.out.println("Connection closed: " + session.getId() + ", reason: " + closeReason.getReasonPhrase());
    }

    // 出现错误时触发
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("Error on connection: " + session.getId() + ", error: " + throwable.getMessage());
    }

    // 广播消息给所有客户端
    private static void broadcast(String message) {
        for (Session client : clients) {
            try {
                client.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

